package com.guxingke.typecho4j.widget.provider.content;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.guxingke.typecho4j.jfinal.model.Content;
import com.guxingke.typecho4j.util.ControllerUtil;
import com.guxingke.typecho4j.util.PageBean;
import com.guxingke.typecho4j.util.PageUtil;
import com.guxingke.typecho4j.util.StringUtil;
import com.guxingke.typecho4j.widget.WidgetProvider;
import com.guxingke.typecho4j.widget.provider.ContentBaseWidget;
import com.jfinal.core.Controller;

/**
 * 归档内容组件<br>
 * 
 * @author guxingke
 * */
public class ArchivesWidget extends ContentBaseWidget implements WidgetProvider {
	private Map<String, List<Content>> categoryCache = new HashMap<String, List<Content>>();
	private Map<String, Long> postsNumCache = new HashMap<String, Long>();

	@Override
	public void excute(Controller controller) {

		Integer page = controller.getParaToInt("page");
		if (page == null) {
			page = 1;
		}

		Integer pageSize = constants.getPageSize();
		String tag = ControllerUtil.getDispatcherKey(controller);
		String prop = ControllerUtil.getUrlPara(controller);

		String keyword = controller.getPara("keyword");
		if ("/search".equals(tag) && keyword != null) {
			prop = keyword;
		}

		controller.setAttr(
				"posts",
				getPostsByTagAndPage(tag, prop, new PageBean(
						page, pageSize)));

		Integer tagTotal = (int) (long) getPostsCountByTagAndAttr(tag,
				prop);
		controller.setAttr("pageNav",
				PageUtil.getPagation(constants.getSiteUrl()
						+ "/" + tag + "/" + prop,
						tagTotal, page, pageSize));

		controller.setAttr("pageInfo",
				StringUtil.getStringByTag(tag, prop));
	}

	private Long getPostsCountByTagAndAttr(String tag, String prop) {

		if (postsNumCache.containsKey(tag)) {
			return postsNumCache.get(tag);
		}

		Long count = null;

		if ("/search".equals(tag)) {
			return getSearchPostsTotal(prop);
		} else if ("/author".equals(tag)) {
			count = getAuthorPostsTotal(prop);
		} else if ("/category".equals(tag)) {
			count = getCategoryPostsTotal(prop);
		} else if ("/tag".equals(tag)) {
			count = getTagPostsTotal(prop);
		} else if ("/archive".equals(tag)) {
			count = getArchivePostsTotal(prop);
		}

		if (count != null) {
			postsNumCache.put(tag, count);
		}

		return count;
	}

	private List<Content> getPostsByTagAndPage(String tag, String prop,
			PageBean pageBean) {
		int page = pageBean.getPage();
		String key = tag + "-" + prop + "-" + page;
		if (categoryCache.containsKey(key)) {
			return categoryCache.get(key);
		}
		List<Content> results = getPostsByQueryInfo(tag, prop, pageBean);
		categoryCache.put(key, results);
		return results;
	}

	@Override
	public void refresh() {
		// 重置缓存
		this.categoryCache.clear();
	}

}
